# 练习:
#     sklearn读取波士顿数据集
#     降维到5维特征
#     切分训练集和测试集
#     训练模型
#     预测测试集结果和mse

from sklearn.datasets import load_boston
from sklearn.decomposition import TruncatedSVD
from sklearn.model_selection import train_test_split

data = load_boston()
x = data.data
y = data.target

#使用截断svd，实现降维=5
x = TruncatedSVD(n_components=5).fit_transform(x)

#分割数据集
x_train, x_test, y_train, y_test = train_test_split(x, y)

from tensorflow.keras import models, layers, losses, optimizers

# 使用layers模块定义各层,并手动连接形成模型
input = layers.Input(shape=5)
out = layers.Dense(1)(input)
model = models.Model(input, out)  #使用models.Model创建模型,指定模型输入和输出
#配置模型
model.compile(optimizer=optimizers.Adadelta(0.5), loss=losses.mse)

#训练模型,返回训练数据history
history = model.fit(x_train, y_train, epochs=200, validation_data=(x_test, y_test)) #validation_data验证集

y_ = model.predict(x_test)
print('预测结果', y_)
# print(losses.mse(y_test, y_))

loss = history.history['loss']      #训练集损失
val_loss = history.history['val_loss']  #验证集损失

import matplotlib.pyplot as plt
plt.plot(loss)
plt.plot(val_loss)
plt.show()



